﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using Monk.Site.Assistant;
using Monk.Site.Models;
using System.Web.Mvc;

namespace Monk.Site.Filters
{
    public class FormValidationFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // 将验证配置对象添加到路由表中
            filterContext.RouteData.Values.Add(BackendKeys.FormValidation, FormValidation.GetConfigureObj());

            base.OnActionExecuting(filterContext);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {

            base.OnActionExecuted(filterContext);
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var area = filterContext.RouteData.DataTokens["area"];
            var controller = filterContext.RouteData.Values["controller"];
            var action = filterContext.RouteData.Values["action"];
            var id = filterContext.RouteData.Values["id"];
            var formValidationData = filterContext.RouteData.Values[BackendKeys.FormValidation] as FormValidationModel;

            ViewModel vm = formValidationData.Views.Where(u => u.Area.ToLower() == (area == null ? "" : area.ToString().ToLower()) && u.Controller.ToLower() == controller.ToString().ToLower() && u.Action.ToLower() == action.ToString().ToLower()).FirstOrDefault();

            if (vm != null)
            {
                ActionResult aresult = filterContext.Result;
                if (aresult is ViewResult)
                {
                    ViewResult vresult = aresult as ViewResult;
                    vm.Fields.ForEach(u =>
                    {
                        vresult.ViewData["v_" + u.Field] = u;
                    });

                    filterContext.Result = vresult;
                }
            }

            base.OnResultExecuting(filterContext);
        }
    }
}